<template>
	<view class="navigation">
		<view class="top-view">
			<eui-nav-bar ref="BcmNavBar" title="订单查询" :storeName="sUserStoreName" :storeId="sUserStore" @onClickStore="clickStore" color="#333" backgroundColor="white" @onClickRefresh="onClickRefresh" />
			<view style="background-color: #fff;">
				<eui-search-bar v-model="searchValue" @confirm="searchConfirm" radius="100" @clear="clearSearch"
					leftIcon="icon-saoyisao" @leftIconClick="scanCode" placeholder="请输入订单号/订单序号/手机后4位"
					:modalValue="searchText" :focus="true">
				</eui-search-bar>
			</view>
		</view>
		<view class="main-view" :style="{ height: '300rpx' }">
			<eui-virtual-list @onRefresh="listPullDown" @lower="listPullUp" refresher="true" isBottom="true" :origList="orderList" type="list" :showHeard="false">
				<template v-slot:list="scope">
					<OrderItem v-if="scope.orderId" :scope="scope" :currentTime="currentTime"
						:chnl-type-list="chnlTypeList" :order-status-list="orderStatusList"
						:delivery-status-list="deliveryStatusList" :pick-type-list="pickTypeList"
						v-model:showContactPop="showContactPop" v-model:logisticsCode="logisticsCode"
						v-model:deliverList="deliverList" :logistics-code-list="logisticsCodeList"
						:order-action="orderAction" v-model:showDeliveryPop="showDeliveryPop"
						v-model:showShipPhonePop="showShipPhonePop" :delivery-time-type-list="deliveryTimeTypeList"
						@print="setPrint" v-model:showPop="showPop" v-model="orderItem"
						:showConfigModal="showConfigModal" />
				</template>
				<template v-slot:bottom="scope">
					<view v-if="scope.orderStatus" class="flex align-center">
						<OrderOperateBtn :scope="scope" @close="close" @fetchData="fetch"
							v-model:currentItem="currentItem" v-model="orderItem"
							v-model:showOrderPickupPop="showOrderPickupPop" v-model:modalType="modalType"
							v-model:showCancelOrderPopup="showCancelOrderPopup" v-model:isOrderCancel="isOrderCancel"
							v-model:title="title" v-model:showDeliveryCancelPopup="showDeliveryCancelPopup"
							v-model:showAuditSendAfsPopup="showAuditSendAfsPopup" v-model:dealType="dealType"
							v-model:dealList="dealList" v-model:showConfirmApplyOrderPopup="showConfirmApplyOrderPopup"
							@orderItemPrint="setPrint" v-model:billType="billType" :showConfigModal="showConfigModal" />
					</view>
				</template>
			</eui-virtual-list>

			<!-- 顾客地址弹窗 -->
			<CustAddressPopup :show="showPop" :scope="orderItem" @close="showPop = false" :title="popupTitleType"
				:addressKey="addressKey" />
			<!-- 联系顾客弹窗 -->
			<CustContactPopup :show="showContactPop" :scope="orderItem" @close="showContactPop = false"
				:orderType="popupOrderType" />
			<!-- 物流信息弹窗 -->
			<DeliveryPopup :show="showDeliveryPop" :scope="orderItem" @close="closeDeliveryPopup"
				:deliverList="deliverList" :logisticsCode="logisticsCode" :orderType="popupOrderType" />
			<!-- 配送员弹窗 -->
			<ShipContactPopup :show="showShipPhonePop" :scope="orderItem" @close="showShipPhonePop = false" />
			<!-- 拣货弹窗 -->
			<OrderPickPopup :show="showOrderPickupPop" :scope="orderItem" @close="showOrderPickupPop = false"
				@orderAction="orderAction" />
			<!-- 取消配送弹窗 -->
			<DeliveryCancelPopup :show="showDeliveryCancelPopup" @close="close" :scope="orderItem"
				@select="selectDeliveryCancelItem" @inputchange="inputDeliveryChange" :billType="billType">
				<template v-slot="">
					<view class="bottom-1">
						<eui-button type="primary" title="确认" style="width: 50%;" singleTag="deliveryCancelSure"
							@click="deliveryCancelSure" />
					</view>
				</template>
			</DeliveryCancelPopup>
			<!-- 取消订单、拒单、驳回入库申请弹窗 -->
			<CancelOrderPopup :show="showCancelOrderPopup" @close="close" :scope="orderItem" :title="title"
				:modalType="modalType" :dealList="dealList" :orderCancelReasonType="orderCancelReasonType"
				@select="selectItem" @inputchange="inputChange">
				<template v-slot="">
					<view class="bottom-1">
						<eui-button type="primary" title="确认" style="width: 50%;"
							@click="orderSureCancel(orderItem, modalType, isOrderCancel, dealType, orderCancelReasonType, rejectReason, orderAction, showConfigModal)" />
					</view>
				</template>
			</CancelOrderPopup>
		</view>
	</view>
</template>
<script setup type="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { storeToRefs } from "pinia";
import service from '@/common/service';
import { useBcmConfig } from '../../../hooks/useBcmConfig';
import { getBcmUrl, bcmRequest } from '../../../hooks/bcmServices';
import { getBcmDictList, getBcmDictLists } from '../../../hooks/bcmUseUntils';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { init, onClickRefresh } from '../../../hooks/bcmInit';
import Enjoy from "../../../common/enjoy";
import OrderItem from './components/OrderItem.vue';
import OrderOperateBtn from './components/OrderOperateBtn.vue'
import CustContactPopup from './components/CustContactPopup.vue'
import CustAddressPopup from './components/CustAddressPopup.vue'
import ShipContactPopup from './components/ContactShipPopup.vue'
import DeliveryPopup from './components/DeliveryPopup.vue'
import OrderPickPopup from './components/OrderPickPopup.vue'
import DeliveryCancelPopup from './components/DeliveryCancelPopup.vue'
import CancelOrderPopup from './components/CancelOrderPopup.vue'
import { orderSureCancel } from './utils/cancelOrder.js'
// import { handleBLEdevicess } from '../utils/PrintFormatUtil.js'
import { getPrintData } from '../utils/PrintFormatUtil.js'
import BluetoothPrinter from '@/common/BluetoothPrinter';
import { useMainStore } from "@/store/modules/store";
import { usePrinterStore } from "@/store/printerStore";
import { usePrintTaskStore } from "@/store/usePrintTaskStore";
import BcmEventType from "../common/BcmEventType";

const mainStore = useMainStore();
const { loginInfo } = mainStore;
const printerStore = usePrinterStore();
const { addTask } = usePrintTaskStore();
const { printTimes, bluetoothPrinter } = storeToRefs(printerStore);
const { getBcmConfigValue, bcmConfig } = useBcmConfig();

const bcmUrl = getBcmUrl()
const timer = ref(null)
const showConfigModal = ref(false);
const BcmNavBar = ref(null);
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');

const CurrentPage = ref(1); //第几页
const PageSize = ref(5); //每页10条
const RowsCount = ref(0); //总条数
const PageCount = ref(1); //总页数
const orderList = ref([]); //列表数据
const searchValue = ref('');//搜索关键字

const searchText = ref('')

//弹窗
const showDeliveryCancelPopup = ref(false)
const showPop = ref(false)
const showContactPop = ref(false)
const showShipPhonePop = ref(false)
const showDeliveryPop = ref(false)
const showOrderPickupPop = ref(false)
const isOrderCancel = ref(false)
const showCancelOrderPopup = ref(false)
const showConfirmApplyOrderPopup = ref(false)
const showAuditSendAfsPopup = ref(false)

//字典
const chnlTypeList = ref([])
const orderStatusList = ref([])
const deliveryStatusList = ref([])
const pickTypeList = ref([])
const deliveryTimeTypeList = ref([])
const logisticsCodeList = ref([])
const afsOrderStatusList = ref([])
const dealTypeList = ref([])
const returnGoodsTypeList = ref([])

const orderCancelReasonType = ref('')
const rejectReason = ref('')
const orderDeliveryCancelReasonType = ref(null)
const orderDeliveryCancelReason = ref('')
const orderItem = ref({})
const currentItem = ref({})
const modalType = ref('cancel')
const title = ref('取消订单原因')
const dealType = ref('3')
const dealList = ref([])
const deliverList = ref([])
const logisticsCode = ref('')
const billType = ref('1')

const isPrinting = ref(false)
const isSkip = ref(false)

const currentTime = ref(null)

watch(() => bcmConfig.value, (newVal) => {
	if (newVal) {
		showConfigModal.value = getBcmConfigValue() == '1' || false;
	}
}, { immediate: true });

const selectItem = function (item) {
	orderCancelReasonType.value = item.detail.value;
}

const selectDeliveryCancelItem = function (item) {
	orderDeliveryCancelReasonType.value = item;
}

const inputChange = function (e) {
	rejectReason.value = e.detail.value;
}

const inputDeliveryChange = function (e) {
	orderDeliveryCancelReason.value = e.detail.value;
}

const addressKey = computed(() => {
	return orderItem.value.afsrderStatus ? 'pickUpAddress' : 'consigneeAddress'
})

const popupOrderType = computed(() => {
	return orderItem.value.afsrderStatus ? 'afs' : 'order'
})

const popupTitleType = computed(() => {
	return orderItem.value.afsrderStatus ? '取件地址' : '顾客地址'
})

const closeDeliveryPopup = () => {
	showDeliveryPop.value = false;
	deliverList.value = []
}

const addPrintTaskFn = function (v, type = 'order', isAutoPrint = false) {
	addTask({
		id: type == 'order' ? v.orderNo : v.afsOrderNo,
		task: async () => await handleTaskPrint(v, type, isAutoPrint)
	})
}

const handleTaskPrint = function (order, type, isAutoPrint = false) {
	return new Promise((resolve) => {
		let data = getPrintData(order, type, printTimes.value), skip = isAutoPrint ? '0' : (isSkip.value ? '1' : '0');
		BluetoothPrinter.setDevice(bluetoothPrinter.value).checkAndPrint(data).then((res) => {
			if (res.code == '0') {
				if (type == 'afs') {
					ConfirmAfsOrderPrint(order, skip)
				} else {
					ConfirmOrderPrint(order, skip)
				}
			}
			resolve()
		}).catch(res => {
			if (!isAutoPrint) {
				skipFunc(res?.msg);
			}
		})
	})
}

const skipFunc = function (contenet = '打印失败，是否跳过打印流程进行后续操作？') {
	uni.showModal({
		title: '提示',
		content: contenet,
		showCancel: true,
		mask: true,
		success: (res) => {
			if (res.confirm) {
				isSkip.value = true;
				isPrinting.value = false;
				ConfirmOrderPrint(orderItem.value, '1')
			} else {
				skipReset()
			}
		}
	})
}

const setPrint = function (v, type = 'order', isAutoPrint = false) {
	orderItem.value = v;
	return new Promise((resolve, reject) => {
		if (mainStore.enjoyServiceIp && mainStore.enjoyServiceIp.EnjoyBCM) {
			if (!isAutoPrint) {
				if (!bluetoothPrinter.value?.deviceId) {
					skipFunc("未设置蓝牙打印机，是否跳过打印？")
					return;
				}
				addPrintTaskFn(v, type, isAutoPrint)
			} else {
				console.log("当前未设置蓝牙打印机");
				// skipFunc("当前未设置蓝牙打印机，是否跳过打印？")
			}
		}
	})
}

const skipReset = () => {
	isPrinting.value = false;
	isSkip.value = false;
}

const ConfirmAfsOrderPrint = (v, skipPrintFlag = '0') => {
	orderAction({
		uniqueKey: '售后单表',
		methodName: 'ConfirmAfsOrderPrint'
	}, v, {
		afsOrderNo: v.afsOrderNo,
		afsOrderId: v.afsOrderId,
		BillId: v.afsOrderId,
		thirdAfsOrderNo: v.thirdAfsOrderNo,
		extras: {
			operateMode: '手动',
			operateTerminal: 'APP',
			skipPrintFlag
		}
	})
}

const ConfirmOrderPrint = (v, skip = undefined) => {
	orderAction({
		uniqueKey: '订单表',
		methodName: 'confirmOrderPrint'
	}, v, {
		operateMode: '手动',
		operateTerminal: 'APP',
		skipPrintFlag: skip ?? (isSkip.value ? '1' : '0')
	})
}

const orderItemPrint = (v) => {
	// if (!isPrinting.value) {
	// 	isPrinting.value = true
	// 	service.enjoyShowLoading()
	// 	handleBLEdevicess({
	// 		v,
	// 		type: 'order',
	// 		reset: {
	// 			skip,
	// 			skipCancel
	// 		}
	// 	}).then(() => {
	// 		ConfirmOrderPrint(v)
	// 	}).finally(() => {
	// 		service.enjoyHideLoading();
	// 		skipCancel()
	// 	})
	// } else {
	// 	console.log('正在打印中...')
	// }
}

const startTimer = () => {
	stopTimer();
	timer.value = setInterval(() => {
		currentTime.value = new Date().getTime();
	}, 1000);
}

const stopTimer = () => {
	// 停止定时器
	clearInterval(timer.value);
	timer.value = null;
}

const setDefault = async () => {
	sUserStore.value = loginInfo?.sDefaultStore ? loginInfo.sDefaultStore : loginInfo.sUserStore;
	sUserStoreName.value = loginInfo?.sDefaultStoreName ? loginInfo.sDefaultStoreName : loginInfo.sUserStoreName;
	sUser.value = loginInfo.sUser;
}

const initDict = async () => {
	const bcmDictLists = getBcmDictLists(['chnlType', 'orderStatus', 'deliveryStatus', 'pickType', 'deliveryTimeType', 'logisticsCode', 'afsOrderStatus', 'afsOrderStatus', 'dealType', 'returnGoodsType']);
	chnlTypeList.value = bcmDictLists['chnlType'];
	orderStatusList.value = bcmDictLists['orderStatus'];
	deliveryStatusList.value = bcmDictLists['deliveryStatus'];
	pickTypeList.value = bcmDictLists['pickType'];
	deliveryTimeTypeList.value = bcmDictLists['deliveryTimeType'];
	logisticsCodeList.value = bcmDictLists['logisticsCode'];
	afsOrderStatusList.value = bcmDictLists['afsOrderStatus'];
	dealTypeList.value = bcmDictLists['dealType'];
	returnGoodsTypeList.value = bcmDictLists['returnGoodsType'];
}

// 选择框点击事件
const clickStore = () => {
	let parms = Enjoy.GetDialogParms();
	parms.CallBack = SelectionChanged;
	parms.SelectionType = "机构选择";
	parms.SelectedItems = sUserStore.value;
	Enjoy.OpenDialog(parms)
}

const SelectionChanged = (event) => {
	if (event.SelectionType == '机构选择') {
		// 更新机构信息
		let sUserStoreHier = event.BackParms.Type; //层级
		sUserStoreName.value = event.BackParms.Value;
		sUserStore.value = event.BackParms.Key;
		mainStore.switchStore(sUserStoreHier, sUserStore.value, sUserStoreName.value);
		uni.$emit(BcmEventType.SWITCH_STORE, { msg: '切换门店' });
		// 按新条件获取数据
		if(searchValue.value){
			fetchOrderData();
		}
	}
}
// 列表下拉刷新
const listPullDown = (e) => {
	if(searchValue.value){
		orderList.value = []
		fetchOrderData();
	}else{
		uni.showToast({
			duration: 1000,
			icon: 'none',
			title: '请先输入查询条件',
			mask: true,
		});
	}
}
// 列表上拉加载
const listPullUp = (e) => {
	if (CurrentPage.value < PageCount.value) {
		CurrentPage.value = CurrentPage.value + 1;
		fetchOrderData(true);
	}
}

const searchConfirm = (e) => {
	searchValue.value = e.value;
	orderList.value = []
	setTimeout(() => {
		fetchOrderData()
	}, 100)
}

const fetch = () => {
	orderList.value = []
	fetchOrderData()
}

const scanCode = () => {
	uni.scanCode({
		success: function (res) {
			if (res.result != '' && res.result != undefined && res.result != null) {
				searchConfirm({
					value: res.result
				})
			}
		},
	});
}

const clearSearch = () => {
	searchValue.value = '';
	orderList.value = []
}

const close = () => {
	showCancelOrderPopup.value = false;
	showDeliveryCancelPopup.value = false;
	showOrderPickupPop.value = false;
	currentItem.value = {};
	orderItem.value = {};
	modalType.value = '';
	orderCancelReasonType.value = '';
	orderDeliveryCancelReason.value = '';
	orderDeliveryCancelReasonType.value = {};
	rejectReason.value = '';
	isOrderCancel.value = false;
}

const orderAction = async function ({
	uniqueKey,
	methodName
}, v, params = undefined, text = '', popup = false, fn = undefined) {
	service.enjoyShowLoading('正在加载...');
	let param = {
		chnlCode: v.chnlCode,
		chnlType: v.chnlType,
		orderNo: v.orderNo,
		storeCode: v.storeCode,
		thirdOrderNo: v.thirdOrderNo,
		orderId: v.orderId,
		...params,
	}
	const response = await bcmRequest(bcmUrl.orderApi, uniqueKey, methodName, param);
	service.enjoyHideLoading();
	if (text) {
		uni.showToast({
			title: text,
			icon: 'none'
		});
	}
	if (popup) {
		close()
	}
	await fetchOrderData()
	if (fn) {
		fn(v)
	}
	if (params) {
		return response
	}
}

const deliveryCancelSure = () => {
	orderAction({
		uniqueKey: '订单表',
		methodName: 'CancelDelivery'
	}, orderItem.value, {
		orderDeliveryCancelReason: orderDeliveryCancelReasonType.value?.mustInputFlag == '1' ? orderDeliveryCancelReason.value : orderDeliveryCancelReasonType.value?.name,
		orderDeliveryCancelReasonType: orderDeliveryCancelReasonType.value?.code
	}, '取消配送操作成功', true);
}

const fetchOrderData = async (e = undefined) => {
	service.enjoyShowLoading('正在加载...');
	if (!e) {
		CurrentPage.value = 1;
		orderList.value = []
	}
	const param = {
		IsNotPage: false,
		CurrentPage: CurrentPage.value,
		PageSize: PageSize.value,
		extras: {
			isQueryGoodsDetails: true,
			moreQuery: [
				{
					fields: "orderNo,consigneePhoneLast,thirdOrderNo,thirdOrderIndex",
					value: searchValue.value
				}
			]
		},
		WhereList: [{ c_col: "storeCode", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" }]
	}
	const response = await bcmRequest(bcmUrl.orderApi, '订单表', 'EnjoyQueryList', param);
	service.enjoyHideLoading();
	CurrentPage.value = response.CurrentPage; //第几页
	PageSize.value = response.PageSize; //每页10条
	RowsCount.value = response.RowsCount; //总条数
	PageCount.value = response.PageCount; //总页数
	if (response.CurrentPage == 1) {
		orderList.value = response.ReturnObject;
	} else {
		orderList.value = orderList.value.concat(response.ReturnObject);
	}
}

onMounted(() => {
	// chnlTypeList.value = getBcmDictList('chnlType')
})

onShow(() => {
	uni.setStorageSync('ispreviewImage', false)
	startTimer()
	if(searchValue.value){
		fetchOrderData();
	}
})

onLoad(async (options) => {
	await init();
	await initDict();
	await setDefault();
	if (!loginInfo.sUserStore) {
		BcmNavBar.value.onClickStore();
		return;
	}
	if (options.searchText) {
		searchValue.value = options.searchText;
		await fetchOrderData()
	}

	uni.$on('REFRESH_ORDER_SEARCH_DATA', () => {
		fetchOrderData()
	});
})

onUnmounted(() => {
	stopTimer();
	uni.$off('REFRESH_ORDER_SEARCH_DATA')
})

defineExpose({
	SelectionChanged
})
</script>
<style lang="scss" scoped>
@import "../../../main.scss";
@import "../common/common.css";

.navigation {
	display: flex;
	height: 100vh;
	width: 100%;
	flex-direction: column;
	background: #F2F2F2;
}

.top-view {
	width: 100%;
	background: #FFFFFF;
	margin-bottom: 20rpx;
}

.main-view {
	flex: 1;
	flex-direction: column;
	padding: 0 20rpx;
}

::v-deep .list_cell {
  overflow: visible;
  padding-bottom: 14rpx;
  margin-right: 0;
  margin-left: 0;
}

.bottom-1 {
  display: flex;
  justify-content: center;
  flex: 0 0 auto;
  height: 70rpx;
  padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
  background: #fff;
}
</style>